package com.gujiangbo.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/6/13 20:02
 * @Version: 1.0
 * @Description:
 */
public class SpinLockDemo {
    AtomicReference<Thread> reference = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "\t" + "---- come in");
        while (!reference.compareAndSet(null, thread)) {

        }

    }

    public void unLock() {
        Thread thread = Thread.currentThread();
        reference.compareAndSet(thread, null);
        System.out.println(thread.getName() + "\t" + "--task over...");

    }

    public static void main(String[] args) {
        SpinLockDemo spinLock = new SpinLockDemo();

        new Thread(() -> {
            spinLock.lock();
            //暂停5秒钟线程
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLock.unLock();
        }, "A").start();

        //暂停5秒钟线程
        try{TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}

        new Thread(() -> {
            spinLock.lock();
            spinLock.unLock();
        }, "B").start();
    }


}

